import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientInput extends Thread{

	public Socket sock;
	private BufferedReader in;
	private PrintWriter out;
	private String clientinput;
	public ServerInput systemInput;

	public ClientInput(Socket serversock, ServerInput systemInput){
		this.systemInput = systemInput;
		try {
			sock = serversock;		
			in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
			out = new PrintWriter(sock.getOutputStream(), true);
			System.out.println("Client "+ sock.getInetAddress()+":"+sock.getPort());
		}catch (IOException e) {
			e.printStackTrace();
		}
		out.println("Welcome to Telnet...");
	}

	public void clientPrint(String input){
		out.println(input);
	}

	public void run(){
		System.out.println("Clientinput Running");
		try {
			while(!(clientinput = in.readLine()).isEmpty()){
				String temp = "";
				System.out.println("Debug Clientinput: "+clientinput);
				String[] splitString = clientinput.split(" ");
				if(splitString[0].equals("D")){
					temp = splitString[1].replaceAll("\"", "");
					WeightSim.setDisplay(temp);
					out.println("D A");
				}else if(splitString[0].equals("DW")){
					out.println("DW A");
				}else if(splitString[0].equals("S")){
					double tempbrutto = WeightSim.getBrutto();
					if(tempbrutto == 0){
						out.println("ES");
						System.out.println("Debug weight response: "+"ES");

					}else{
						out.println("S S "+(tempbrutto-WeightSim.getTara())+" kg");
						System.out.println("Debug weight response: "+"S S "+(tempbrutto-WeightSim.getTara())+" kg");
					}
				}else if(splitString[0].equals("T")){
					WeightSim.setTara();
					out.println("T S "+WeightSim.getBrutto()+" kg");
				}else if(splitString[0].equals("B")){
					out.println(WeightSim.getBrutto()+"kg");
				}else if(splitString[0].equals("RM20")){
					try {
						if(splitString[1].equals("8")){ // RM20 8
							for (int i = 2; i < splitString.length; i++) {
								temp = temp +" "+ splitString[i];
							}
							if(temp.trim().equals("")){
								out.println("Need text");
								continue;
							}
							temp = temp.replaceAll("\"", "");
							out.println("RM20 B");
							systemInput.systemRM20(temp);
						}
					} catch (IndexOutOfBoundsException e) {
						e.printStackTrace();
					}

				}else if(splitString[0].equals("Q")){
					WeightSim.close();
				}else{
					systemInput.test();
					out.println("Unknown command!");
				}
			}
		}catch (IOException e) {
		}catch (NullPointerException e){
			System.out.println("Client quit the ganme!");
		}
	}
}
